package cn.spdb.harrier.rpc.client;

import java.lang.reflect.InvocationTargetException;

import cn.spdb.harrier.common.utils.URI;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;

public class RpcClient implements InterfaceRpcClient {

	private static class RpcClientIner {
		private static RpcClient instance = new RpcClient();
	}

	public static RpcClient getInstance() {
		return RpcClientIner.instance;
	}

@Override
public <T> T create(Class<T> clazz, URI uri) throws InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
    // 使用 ByteBuddy 动态生成指定接口的子类
    return new ByteBuddy()
            .subclass(clazz) // 指定要创建的子类类型
            .method(ElementMatchers.isDeclaredBy(clazz)) // 匹配接口中声明的所有方法
            .intercept(MethodDelegation.to(new ConsumerInterceptor(uri))) // 将方法调用委托给 ConsumerInterceptor 实例进行处理
            .make() // 生成字节码
            .load(getClass().getClassLoader()) // 加载新生成的类
            .getLoaded() // 获取已加载的 Class 对象
            .getDeclaredConstructor() // 获取无参构造函数
            .newInstance(); // 创建实例并返回
}

	

}
